import BaseTable from "@/components/Table/BaseTable";
import { useCallback, useEffect, useState, useRef } from "react";
import { INIT_PAGINATION } from "@/utils/config";
import type { PagePermission, TableOptions } from "@/types/public";
import { usePublicStore } from "@/stores";
import { useCommonStore } from "@/hooks/useCommonStore";
import { checkPermission } from "@/utils/permissions";
import BaseContent from "@/components/Content/BaseContent";
import { EditTwoTone, DeleteTwoTone } from "@ant-design/icons";
import { type FormInstance } from "antd";
import { searchList, tableColumns, createList } from "./model";
import BaseSearch from "@/components/Search/BaseSearch";
import BasePagination from "@/components/Pagination/BasePagination";
import BaseCard from "@/components/Card/BaseCard";
import BaseModal from "@/components/Modal/BaseModal";
import BaseForm from "@/components/Form/BaseForm";
import type { BaseFormData } from "@/types/form";

// 当前行数据
interface RowData {
    id: string;
}

function Goods() {
    const [isFetch, setFetch] = useState(false);
    const [page, setPage] = useState(INIT_PAGINATION.page);
    const [pageSize, setPageSize] = useState(INIT_PAGINATION.pageSize);
    const [total, setTotal] = useState(0);
    const [tableData, setTableData] = useState<BaseFormData[]>([]);
    const [searchData, setSearchData] = useState({});
    const isRefreshPage = usePublicStore((state) => state.isRefreshPage);
    const setRefreshPage = usePublicStore((state) => state.setRefreshPage);
    const { permissions } = useCommonStore();
    const [isLoading, setLoading] = useState(false);
    const [isCreateOpen, setCreateOpen] = useState(false);
    const [createTitle, setCreateTitle] = useState("");
    const [createId, setCreateId] = useState("");
    const [createData, setCreateData] = useState({});
    const [isCreateLoading, setCreateLoading] = useState(false);
    const createFormRef = useRef<FormInstance>(null);

    // 权限前缀
    const permissionPrefix = "/system";
    const pagePermission: PagePermission = {
        page: checkPermission(`${permissionPrefix}/user`, permissions),
    };

    /** 获取表格数据 */
    const getPage = useCallback(async () => {
        const params = { ...searchData, page, pageSize };
        console.log(createId);
        try {
            setLoading(true);
            console.log(params);
            setTimeout(() => {
                setTableData([{ username: "username", id: "11" }]);
                setTotal(1);
            }, 300);
        } finally {
            setFetch(false);
            setLoading(false);
        }
    }, [page, pageSize, searchData]);
    const onSearch = (values: FormData) => {
        setPage(1);
        setSearchData(values);
        setFetch(true);
    };

    // 首次进入自动加载接口数据
    useEffect(() => {
        getPage();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // 如果是新增或编辑成功重新加载页面
    useEffect(() => {
        if (isRefreshPage) {
            setRefreshPage(false);
            getPage();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isRefreshPage]);

    useEffect(() => {
        if (isFetch) getPage();
    }, [getPage, isFetch]);

    const onChangePagination = (page: number, pageSize: number) => {
        setPage(page);
        setPageSize(pageSize);
        setFetch(true);
    };

    const optionRender: TableOptions<object> = (_, record) => (
        <>
            {<EditTwoTone style={{ marginLeft: 5 }} onClick={() => onDelete((record as RowData).id)} />}
            {<DeleteTwoTone style={{ marginLeft: 15 }} twoToneColor="#ef0a38" onClick={() => onDelete((record as RowData).id)} />}
        </>
    );

    const onDelete = async (id: string) => {
        try {
            console.log(id);
            setLoading(true);
        } finally {
            setLoading(false);
        }
    };

    const onCreate = () => {
        setCreateOpen(true);
        setCreateTitle("新增货物");
        setCreateId("");
        setCreateData({});
    };

    /** 表格提交 */
    const createSubmit = () => {
        createFormRef.current?.submit();
    };

    /** 关闭新增/修改弹窗 */
    const closeCreate = () => {
        setCreateOpen(false);
    };

    const handleCreate = async (values) => {
        try {
            setCreateLoading(true);
            console.log(values);
            setCreateOpen(false);
            getPage();
        } finally {
            setCreateLoading(false);
        }
    };

    return (
        <>
            <BaseContent isPermission={pagePermission.page}>
                <BaseCard>
                    <BaseSearch list={searchList()} data={searchData} isLoading={isLoading} handleFinish={onSearch} />
                </BaseCard>

                <BaseCard className="mt-10px">
                    <BaseTable
                        isLoading={isLoading}
                        columns={tableColumns(optionRender)}
                        dataSource={tableData}
                        getPage={getPage}
                        isCreate
                        onCreate={onCreate}
                    />
                    <BasePagination disabled={isLoading} current={page} pageSize={pageSize} total={total} onChange={onChangePagination} />
                </BaseCard>

                <BaseModal title={createTitle} open={isCreateOpen} confirmLoading={isCreateLoading} onOk={createSubmit} onCancel={closeCreate}>
                    <BaseForm ref={createFormRef} list={createList()} data={createData} labelCol={{ span: 5 }} handleFinish={handleCreate} />
                </BaseModal>
            </BaseContent>
        </>
    );
}

export default Goods;
